import { addUser, queryUsers, deleteUser, updateUser } from "@/services/user";
import { 
    queryGroups, addGroup, deleteGroup, updateGroup, updateGroupUsers,
    queryDisks, addDisk, deleteDisk, updateDisk,
    queryUserAudit,
} from "./service";
import { getOrderBit, batchRes } from "@/generic/Utils";
import { MOULD_MARK } from "@/generic/ConfigParams";

export default {
    namespace: 'manager',
    state: {
        currentUser: {},
        data: [],
        isOpts: true,
        modalVisible: false,
        checkedRows: [],
        currentPage: null,
        objInfo: {},
        MARK: null,
    },
    effects: {
        *methodAdapter({ payload, method }, { _, put, select }) { // payload = {method, ...}
            console.log("==>> methodAdapter is enter!", payload, method)
            if (method) {
                const requests = {
                    query: [queryUsers, queryGroups, queryDisks, ],
                    add: [addUser, addGroup, addDisk],
                    delete: [deleteUser, deleteGroup, deleteDisk],
                    update: [updateUser, updateGroup, updateDisk],
                };
                const manager = yield select(state => state.manager);
                let response = null;
                const _method = requests[method]
                switch (manager.MARK) {
                    case MOULD_MARK.Group:
                        response = yield put({ type: method, request: _method[1], payload });
                        break;
                    case MOULD_MARK.Vdisk:
                        response = yield put({ type: method, request: _method[2], payload });
                        break;
                    case MOULD_MARK.folder:
                        response = yield put({ type: method, request: _method[3], payload });
                        break;

                    default:
                        response = yield put({ type: method, request: _method[0], payload });
                        break;
                }

                return response
            }
        },

        *query({ request:queryRequest, payload = {} }, { call, put }) {
            // console.log('===>> query', queryRequest)
            if (queryRequest) {
                const response = yield call(queryRequest, payload, true);
                console.log('===>> response', response)
                if (response.results) {
                    yield put({
                        type: 'updateData',
                        payload: response.results
                    })
                }
                return response;
            }
        },
        *add({ request: addRequest, payload }, { call, put }){
            console.log("==..> add", payload)
            const args = {};
            if (payload.fields && payload.fields instanceof Object) {
                for (const key in payload.fields) {
                    args[key] = payload.fields[key];
                }
            }

            const response = yield call(addRequest, args)
            if (response.ok) {
                yield put({ type: 'methodAdapter', method: 'query', payload: {} })
            }
            return response;
        },
        *delete({ request: deleteRequest, payload }, { call, put }) { 
            console.log("==..> delete", payload)
            // 实现批量删除用户 or 单个用户
            if (payload.rows.length > 0) {
                // 不能删除已经＂启用＂的账号
                let isEnable = false;
                for (const item of payload.rows) {
                    if (item.enable) {
                        isEnable = true;
                        break;
                    }
                }
                if (!isEnable) {
                    const response = yield batchRes(deleteRequest, payload, call)
                    if (response.ok) {
                        yield put({ type: 'methodAdapter', method: 'query', payload: {} })
                    }
                    return response;
                }
                // statusText 中文必须解码，不然会报错。
                const init = { ok: false, status: 405, statusText: encodeURI("无法删除已启用的账号") };
                return new Response(new Blob(), init)
            }
        },
        *update({ request: updateRequest, payload }, { call, put }) {
            console.log("==..> updateRequest", payload)
            if (payload.rows && updateRequest) {
                const response = yield batchRes(updateRequest, payload, call)
                if (response.ok) {
                    yield put({ type: 'methodAdapter', method: 'query', payload: {} })

                    if (payload.rows.length == 1) {
                        yield put({ type: 'updateCurrentPage', payload: { objInfo: payload.rows[0] } })
                    }
                }

                return response;
            }
         },
    },
    reducers: {
        updateOpts(state, { payload }) {
            // return { ...state, isOpts: payload}
            return { ...state, isOpts: !state.isOpts }
        },

        pageSkipping(state, { payload = {} }) {
            console.log('==>> pageSkipping', payload)
            return { ...state, isOpts: payload.isOpts, MARK: payload.mark }
        },

        updateData(state, { payload = [] }) {
            // data更新时，永远把checkedRows初始为[]
            // console.log('==>> updateData', payload)
            if (payload.length > 0) {
                const orderBit = getOrderBit(payload.length);
                orderBit && payload.forEach((item, i) => {
                    item.key = `${i + 1}`.padStart(orderBit, "0");
                })
            }
            return { ...state, data: payload, checkedRows: [] }
        },

        updateModalVisible(state, { payload = {} }) {
            return { ...state, modalVisible: payload.value }
        },

        updateCheckedRows(state, { payload = [] }) {
            // console.log("===>> updateCheckedRows", payload)
            return { ...state, checkedRows: payload }
        },

        updateCurrentPage(state, { payload }) {
            let page = null;
            if (typeof (payload) == "undefined") {
                page = state.currentPage;
            }
            else {
                page = payload ? payload.mark : page;
            }
            return { 
                ...state, currentPage: page, 
                objInfo: payload ? payload.record : state.objInfo,
            }
        }
    }
}